package com.lzy.cloud.base.controller;

import com.github.pagehelper.PageInfo;
import com.lzy.cloud.base.dto.BaseCategoryDto;
import com.lzy.cloud.base.request.BaseCategoryRequest;
import com.lzy.cloud.base.response.BaseCategoryResponse;
import com.lzy.cloud.base.service.CategoryService;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.orm.db.Pager;
import com.lzy.framework.core.output.Result;
import com.lzy.framework.core.utils.DozerUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 项目表
 */
@RestController
@RequestMapping(value = "/category")
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 列表
     * @param request
     * @return
     */
    @RequestMapping(value = "/list")
    public Result list(@RequestBody BaseCategoryRequest request){
        Pager pager = new Pager();
        pager.setPageNum(request.getPageNum());
        pager.setPageSize(request.getPageSize());
        PageInfo<BaseCategoryDto> pageInfo = categoryService.getList(pager);
        List<BaseCategoryDto> list = pageInfo.getList();
        if (pageInfo != null && pageInfo.getList() != null) {
            return new Result(pager, DozerUtils.maps(list, BaseCategoryResponse.class));
        } else {
            return new Result();
        }
    }

    /**
     * 获取详情
     * @param id
     * @return
     */
    @RequestMapping(value = "/find/{id}",method = RequestMethod.GET)
    public Result find(@PathVariable Long id){
        return new Result(categoryService.findById(id));
    }

    /**
     * 新增
     * @param request
     * @return
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public Result add(@RequestBody BaseCategoryRequest request){
        Long id = categoryService.insert(DozerUtils.map(request,BaseCategoryDto.class));
        Ensure.that(id>0).isTrue("00030002");
        return new Result(id);
    }

    /**
     * 修改
     * @param request
     * @return
     */
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public Result update(@RequestBody BaseCategoryRequest request){
        int count = categoryService.update(DozerUtils.map(request,BaseCategoryDto.class));
        Ensure.that(count>0).isTrue("00030003");
        return new Result();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete/{id}")
    public Result delete(@PathVariable Long id){
        int count = categoryService.deleteById(id);
        Ensure.that(count>0).isTrue("00030003");
        return new Result();
    }

}
